<!DOCTYPE html>
<html lang="zh" dir="ltr" class="client-nojs">
<head>
<title>基于范围的 for 循环 (C++11 起)</title>
<meta charset="UTF-8">
<meta name="generator" content="MediaWiki 1.21.2">
<link rel="shortcut icon" href="../../../common/favicon.ico">
<link rel="stylesheet" href="../../../common/ext.css">
<meta name="ResourceLoaderDynamicStyles" content="">
<link rel="stylesheet" href="../../../common/site_modules.css">
<style>a:lang(ar),a:lang(ckb),a:lang(fa),a:lang(kk-arab),a:lang(mzn),a:lang(ps),a:lang(ur){text-decoration:none}#toc{display:none}.editsection{display:none}
/* cache key: mwiki1-mwiki_zh_:resourceloader:filter:minify-css:7:15cea3ec788a65b5187d4018eed543bf */</style>

<script src="../../../common/startup_scripts.js"></script>
<script>if(window.mw){
mw.config.set({"wgCanonicalNamespace":"","wgCanonicalSpecialPageName":false,"wgNamespaceNumber":0,"wgPageName":"cpp/language/range-for","wgTitle":"cpp/language/range-for","wgCurRevisionId":72921,"wgArticleId":2745,"wgIsArticle":true,"wgAction":"view","wgUserName":null,"wgUserGroups":["*"],"wgCategories":[],"wgBreakFrames":false,"wgPageContentLanguage":"zh","wgSeparatorTransformTable":["",""],"wgDigitTransformTable":["",""],"wgDefaultDateFormat":"zh","wgMonthNames":["","1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"],"wgMonthNamesShort":["","1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"],"wgRelevantPageName":"cpp/language/range-for","wgUserVariant":"zh","wgRestrictionEdit":[],"wgRestrictionMove":[]});
}</script><script>if(window.mw){
mw.loader.implement("user.options",function(){mw.user.options.set({"ccmeonemails":0,"cols":80,"date":"default","diffonly":0,"disablemail":0,"disablesuggest":0,"editfont":"default","editondblclick":0,"editsection":0,"editsectiononrightclick":0,"enotifminoredits":0,"enotifrevealaddr":0,"enotifusertalkpages":1,"enotifwatchlistpages":0,"extendwatchlist":0,"externaldiff":0,"externaleditor":0,"fancysig":0,"forceeditsummary":0,"gender":"unknown","hideminor":0,"hidepatrolled":0,"imagesize":2,"justify":0,"math":1,"minordefault":0,"newpageshidepatrolled":0,"nocache":0,"noconvertlink":0,"norollbackdiff":0,"numberheadings":0,"previewonfirst":0,"previewontop":1,"quickbar":5,"rcdays":7,"rclimit":50,"rememberpassword":0,"rows":25,"searchlimit":20,"showhiddencats":0,"showjumplinks":1,"shownumberswatching":1,"showtoc":0,"showtoolbar":1,"skin":"cppreference2","stubthreshold":0,"thumbsize":2,"underline":2,"uselivepreview":0,"usenewrc":0,"watchcreations":0,"watchdefault":0,"watchdeletion":0,
"watchlistdays":3,"watchlisthideanons":0,"watchlisthidebots":0,"watchlisthideliu":0,"watchlisthideminor":0,"watchlisthideown":0,"watchlisthidepatrolled":0,"watchmoves":0,"wllimit":250,"variant":"zh","language":"zh","searchNs0":true,"searchNs1":false,"searchNs2":false,"searchNs3":false,"searchNs4":false,"searchNs5":false,"searchNs6":false,"searchNs7":false,"searchNs8":false,"searchNs9":false,"searchNs10":false,"searchNs11":false,"searchNs12":false,"searchNs13":false,"searchNs14":false,"searchNs15":false,"gadget-MathJax":1,"gadget-ColiruCompiler":1});;},{},{});mw.loader.implement("user.tokens",function(){mw.user.tokens.set({"editToken":"+\\","patrolToken":false,"watchToken":false});;},{},{});
/* cache key: mwiki1-mwiki_zh_:resourceloader:filter:minify-js:7:258d7cd6aa9aa67dee25e01fb6a9e505 */
}</script>
<script>if(window.mw){
mw.loader.load(["mediawiki.page.startup","mediawiki.legacy.wikibits","mediawiki.legacy.ajax"]);
}</script>
<style type="text/css">/*<![CDATA[*/
.source-cpp {line-height: normal;}
.source-cpp li, .source-cpp pre {
	line-height: normal; border: 0px none white;
}
/**
 * GeSHi Dynamically Generated Stylesheet
 * --------------------------------------
 * Dynamically generated stylesheet for cpp
 * CSS class: source-cpp, CSS id: 
 * GeSHi (C) 2004 - 2007 Nigel McNie, 2007 - 2008 Benny Baumann
 * (http://qbnz.com/highlighter/ and http://geshi.org/)
 * --------------------------------------
 */
.cpp.source-cpp .de1, .cpp.source-cpp .de2 {font: normal normal 1em/1.2em monospace; margin:0; padding:0; background:none; vertical-align:top;}
.cpp.source-cpp  {font-family:monospace;}
.cpp.source-cpp .imp {font-weight: bold; color: red;}
.cpp.source-cpp li, .cpp.source-cpp .li1 {font-weight: normal; vertical-align:top;}
.cpp.source-cpp .ln {width:1px;text-align:right;margin:0;padding:0 2px;vertical-align:top;}
.cpp.source-cpp .li2 {font-weight: bold; vertical-align:top;}
.cpp.source-cpp .kw1 {color: #0000dd;}
.cpp.source-cpp .kw2 {color: #0000ff;}
.cpp.source-cpp .kw3 {color: #0000dd;}
.cpp.source-cpp .kw4 {color: #0000ff;}
.cpp.source-cpp .co1 {color: #909090;}
.cpp.source-cpp .co2 {color: #339900;}
.cpp.source-cpp .coMULTI {color: #ff0000; font-style: italic;}
.cpp.source-cpp .es0 {color: #008000; font-weight: bold;}
.cpp.source-cpp .es1 {color: #008000; font-weight: bold;}
.cpp.source-cpp .es2 {color: #008000; font-weight: bold;}
.cpp.source-cpp .es3 {color: #008000; font-weight: bold;}
.cpp.source-cpp .es4 {color: #008000; font-weight: bold;}
.cpp.source-cpp .es5 {color: #008000; font-weight: bold;}
.cpp.source-cpp .br0 {color: #008000;}
.cpp.source-cpp .sy0 {color: #008000;}
.cpp.source-cpp .sy1 {color: #000080;}
.cpp.source-cpp .sy2 {color: #000040;}
.cpp.source-cpp .sy3 {color: #000040;}
.cpp.source-cpp .sy4 {color: #008080;}
.cpp.source-cpp .st0 {color: #008000;}
.cpp.source-cpp .nu0 {color: #000080;}
.cpp.source-cpp .nu6 {color: #000080;}
.cpp.source-cpp .nu8 {color: #000080;}
.cpp.source-cpp .nu12 {color: #000080;}
.cpp.source-cpp .nu16 {color:#000080;}
.cpp.source-cpp .nu17 {color:#000080;}
.cpp.source-cpp .nu18 {color:#000080;}
.cpp.source-cpp .nu19 {color:#000080;}
.cpp.source-cpp .ln-xtra, .cpp.source-cpp li.ln-xtra, .cpp.source-cpp div.ln-xtra {background-color: #ffc;}
.cpp.source-cpp span.xtra { display:block; }

/*]]>*/
</style><style type="text/css">/*<![CDATA[*/
.source-text {line-height: normal;}
.source-text li, .source-text pre {
	line-height: normal; border: 0px none white;
}
/**
 * GeSHi Dynamically Generated Stylesheet
 * --------------------------------------
 * Dynamically generated stylesheet for text
 * CSS class: source-text, CSS id: 
 * GeSHi (C) 2004 - 2007 Nigel McNie, 2007 - 2008 Benny Baumann
 * (http://qbnz.com/highlighter/ and http://geshi.org/)
 * --------------------------------------
 */
.text.source-text .de1, .text.source-text .de2 {font: normal normal 1em/1.2em monospace; margin:0; padding:0; background:none; vertical-align:top;}
.text.source-text  {font-family:monospace;}
.text.source-text .imp {font-weight: bold; color: red;}
.text.source-text li, .text.source-text .li1 {font-weight: normal; vertical-align:top;}
.text.source-text .ln {width:1px;text-align:right;margin:0;padding:0 2px;vertical-align:top;}
.text.source-text .li2 {font-weight: bold; vertical-align:top;}
.text.source-text .ln-xtra, .text.source-text li.ln-xtra, .text.source-text div.ln-xtra {background-color: #ffc;}
.text.source-text span.xtra { display:block; }

/*]]>*/
</style><!--[if lt IE 7]><style type="text/css">body{behavior:url("/mwiki/skins/cppreference2/csshover.min.htc")}</style><![endif]--></head>
<body class="mediawiki ltr sitedir-ltr ns-0 ns-subject page-cpp_language_range-for skin-cppreference2 action-view cpp-navbar">
        <!-- header -->
        <!-- /header -->
        <!-- content -->
<div id="cpp-content-base">
            <div id="content">
                <a id="top"></a>
                <div id="mw-js-message" style="display:none;"></div>
                                <!-- firstHeading -->
<h1 id="firstHeading" class="firstHeading">基于范围的 for 循环 <span class="t-mark-rev t-since-cxx11">(C++11 起)</span></h1>
                <!-- /firstHeading -->
                <!-- bodyContent -->
                <div id="bodyContent">
                                        <!-- tagline -->
                    <div id="siteSub">来自cppreference.com</div>
                    <!-- /tagline -->
                                        <!-- subtitle -->
                    <div id="contentSub"><span class="subpages">&lt; <a href="../../cpp.html" title="cpp">cpp</a>‎ | <a href="../language.html" title="cpp/language">language</a></span></div>
                    <!-- /subtitle -->
                                                            <!-- bodycontent -->
                    <div id="mw-content-text" lang="zh" dir="ltr" class="mw-content-ltr"><div class="t-navbar" style=""><div class="t-navbar-sep"> </div><div class="t-navbar-head"><a href="../../cpp.html" title="cpp"> C++</a><div class="t-navbar-menu"><div><div><table class="t-nv-begin" cellpadding="0" style="line-height:1.1em">
<tr class="t-nv"><td colspan="5"> <a href="../language.html" title="cpp/language">语言</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../header.html" title="cpp/header">标准库头文件</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../freestanding.html" title="cpp/freestanding"> 自立与有宿主实现</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../named_req.html" title="cpp/named req">具名要求</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../utility.html#.E8.AF.AD.E8.A8.80.E6.94.AF.E6.8C.81" title="cpp/utility">语言支持库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../concepts.html" title="cpp/concepts">概念库</a> <span class="t-mark-rev t-since-cxx20">(C++20)</span> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../error.html" title="cpp/error">诊断库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../utility.html" title="cpp/utility">工具库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../string.html" title="cpp/string">字符串库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../container.html" title="cpp/container">容器库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../iterator.html" title="cpp/iterator">迭代器库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../ranges.html" title="cpp/ranges"> 范围库</a> <span class="t-mark-rev t-since-cxx20">(C++20)</span> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../algorithm.html" title="cpp/algorithm">算法库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../numeric.html" title="cpp/numeric">数值库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../locale.html" title="cpp/locale">本地化库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../io.html" title="cpp/io">输入/输出库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../filesystem.html" title="cpp/filesystem">文件系统库</a> <span class="t-mark-rev t-since-cxx17">(C++17)</span> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../regex.html" title="cpp/regex">正则表达式库</a> <span class="t-mark-rev t-since-cxx11">(C++11)</span> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../atomic.html" title="cpp/atomic">原子操作库</a> <span class="t-mark-rev t-since-cxx11">(C++11)</span> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../thread.html" title="cpp/thread">线程支持库</a> <span class="t-mark-rev t-since-cxx11">(C++11)</span> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../experimental.html" title="cpp/experimental">技术规范</a> </td></tr>
</table></div><div></div></div></div></div><div class="t-navbar-sep"> </div><div class="t-navbar-head"><a href="../language.html" title="cpp/language">C++ 语言</a></div><div class="t-navbar-sep"> </div><div class="t-navbar-head"><a href="statements.html" title="cpp/language/statements">语句</a><div class="t-navbar-menu"><div><div style="display:inline-block">
<div><table class="t-nv-begin" cellpadding="0" style="line-height:1.1em">
<tr class="t-nv-h2"><td colspan="5"> 标号 </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="statements.html" title="cpp/language/statements"> <span class="t-spar">label</span> : <span class="t-spar">statement</span></a></td></tr>
<tr class="t-nv-h2"><td colspan="5"> 表达式语句 </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="statements.html" title="cpp/language/statements"> <span class="t-spar">expression</span> ; </a></td></tr>
<tr class="t-nv-h2"><td colspan="5"> 复合语句 </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="statements.html" title="cpp/language/statements"> { <span class="t-spar">statement</span>... } </a></td></tr>
<tr class="t-nv-h2"><td colspan="5"> 选择语句 </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="if.html" title="cpp/language/if"> if</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="switch.html" title="cpp/language/switch"> switch</a></td></tr>
<tr class="t-nv-h2"><td colspan="5"> 循环语句 </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="while.html" title="cpp/language/while"> while</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="do.html" title="cpp/language/do"> do-while</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="for.html" title="cpp/language/for"> for</a></td></tr>
<tr class="t-nv"><td colspan="5"> <strong class="selflink">范围 for</strong><span class="t-mark-rev t-since-cxx11">(C++11)</span></td></tr>
<tr class="t-nv-h2"><td colspan="5"> 跳转语句 </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="break.html" title="cpp/language/break"> break</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="continue.html" title="cpp/language/continue"> continue</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="return.html" title="cpp/language/return"> return</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="goto.html" title="cpp/language/goto"> goto</a></td></tr>
<tr class="t-nv-h2"><td colspan="5"> 声明语句 </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="declarations.html" title="cpp/language/declarations"> <span class="t-spar">declaration</span> ; </a></td></tr>
<tr class="t-nv-h2"><td colspan="5"> try 块 </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="try_catch.html" title="cpp/language/try catch"> try <span class="t-spar">compound-statement</span> <span class="t-spar">handler-sequence</span></a></td></tr>
<tr class="t-nv-h2"><td colspan="5"> 事务性内存 </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="transactional_memory.html" title="cpp/language/transactional memory"> <code>synchronized</code>, <code>atomic_commit</code></a> 等<span class="t-mark-rev t-since-tm-ts t-mark-ts">(TM TS)</span></td></tr>
</table></div>
</div><div></div></div></div></div><div class="t-navbar-sep"> </div></div>
<p>在一个范围上执行 <code>for</code> 循环。
</p><p>用作对范围中的各个值（如容器中的所有元素）进行操作的传统 <a href="for.html" title="cpp/language/for">for 循环</a>的更加可读的等价版本。
</p>
<h3><span class="mw-headline" id=".E8.AF.AD.E6.B3.95">语法</span></h3>
<table class="t-sdsc-begin">

<tr>
<td colspan="10" class="t-sdsc-sep">
</td></tr>
<tr class="t-sdsc">
<td class="t-sdsc-nopad"> <span class="t-spar">属性</span><span class="t-mark">(可选)</span> <code><b>for (</b></code> <span class="t-spar">初始化语句</span><span class="t-mark">(可选)</span><span class="t-spar">范围变量声明</span> <code><b>:</b></code> <span class="t-spar">范围表达式</span> <code><b>)</b></code> <span class="t-spar">循环语句</span>
</td>
<td class="t-sdsc-nopad">
</td>
<td class="t-sdsc-nopad">
</td></tr>



<tr>
<td colspan="10" class="t-sdsc-sep">
</td></tr></table>
<table class="t-par-begin">


<tr class="t-par">
<td>  <span class="t-spar">属性</span>
</td>
<td> -
</td>
<td>  任意数量的<a href="attributes.html" title="cpp/language/attributes">属性</a>
</td></tr>
<tr class="t-par">
<td>  <span class="t-spar">初始化语句</span>
</td>
<td> -
</td>
<td>  <span class="t-mark-rev t-since-cxx20">(C++20 起)</span> 以下之一：
<ul><li> <a href="statements.html" title="cpp/language/statements">表达式语句</a>（可以是<i>空语句</i>“<code><b>;</b></code>”）
</li><li> <a href="declarations.html" title="cpp/language/declarations">简单声明</a>，典型地为带初始化器的变量声明，但它可以声明任意多个变量，或者是<a href="structured_binding.html" title="cpp/language/structured binding">结构化绑定声明</a>
</li></ul>
 <table class="t-rev-begin">
<tr class="t-rev t-since-cxx23"><td>
<ul><li> <a href="type_alias.html" title="cpp/language/type alias">别名声明</a>
</li></ul>
</td>
<td><span class="t-mark-rev t-since-cxx23">(C++23 起)</span></td></tr>
</table>
<dl><dd>注意，所有 <span class="t-spar">初始化语句</span> 必然以分号 <code><b>;</b></code> 结尾，因此它经常被非正式地描述为后随分号的表达式或声明。
</dd></dl>
</td></tr>
<tr class="t-par">
<td>  <span class="t-spar">范围变量声明</span>
</td>
<td> -
</td>
<td>  一个具名变量的<a href="declarations.html" title="cpp/language/declarations">声明</a>，它的类型是由 <span class="t-spar">范围表达式</span> 所表示的序列的元素的类型，或该类型的引用。通常用 <a href="auto.html" title="cpp/language/auto">auto 说明符</a>进行自动类型推导。
</td></tr>
<tr class="t-par">
<td>  <span class="t-spar">范围表达式</span>
</td>
<td> -
</td>
<td>  可以表示一个合适的序列（数组，或定义了 <code>begin</code> 和 <code>end</code> 成员函数或自由函数的对象，见下文）的任意<a href="expressions.html" title="cpp/language/expressions">表达式</a>，或一个<a href="list_initialization.html" title="cpp/language/list initialization">花括号初始化器列表</a>。
</td></tr>
<tr class="t-par">
<td>  <span class="t-spar">循环语句</span>
</td>
<td> -
</td>
<td>  任意<a href="statements.html" title="cpp/language/statements">语句</a>，通常是一条复合语句，它是循环体
</td></tr></table>
 <table class="t-rev-begin">
<tr class="t-rev t-since-cxx17"><td>
<p><span class="t-spar">范围变量声明</span> 可以是<a href="structured_binding.html" title="cpp/language/structured binding">结构化绑定声明</a>：
</p>
<div dir="ltr" class="mw-geshi" style="text-align: left;"><div class="cpp source-cpp"><pre class="de1"><span class="kw1">for</span> <span class="br0">(</span><span class="kw4">auto</span><span class="sy3">&amp;&amp;</span> <span class="br0">[</span>first,second<span class="br0">]</span> <span class="sy4">:</span> mymap<span class="br0">)</span> <span class="br0">{</span>
    <span class="co1">// 使用 first 和 second</span>
<span class="br0">}</span></pre></div></div>
</td>
<td><span class="t-mark-rev t-since-cxx17">(C++17 起)</span></td></tr>
</table>
<h3><span class="mw-headline" id=".E8.A7.A3.E9.87.8A">解释</span></h3>
<p>上述语法产生的代码等价于下列代码（<b><code>__range</code></b>、<b><code>__begin</code></b> 和 <b><code>__end</code></b> 仅用于阐释）：
</p>
 <table class="t-rev-begin">
<tr class="t-rev t-until-cxx17"><td>
<p><code><b>{</b></code><br>
</p>
<dl><dd><code><b>auto &amp;&amp; __range =</b></code> <span class="t-spar">范围表达式</span> <code><b>;</b></code> <br>
</dd><dd><code><b>for (auto __begin =</b></code> <i>首表达式</i><code><b>,</b></code> <code><b>__end =</b></code> <i>尾表达式</i> <code><b>; __begin != __end; ++__begin) {</b></code> <br>
<dl><dd><span class="t-spar">范围变量声明</span> <code><b>= *__begin;</b></code> <br>
</dd><dd><span class="t-spar">循环语句</span> <br>
</dd></dl>
</dd><dd><code><b>} </b></code> <br>
</dd></dl>
<p><code><b>} </b></code> <br>
</p>
</td>
<td><span class="t-mark-rev t-until-cxx17">(C++17 前)</span></td></tr>
<tr class="t-rev t-since-cxx17 t-until-cxx20"><td>
<p><code><b>{</b></code><br>
</p>
<dl><dd><code><b>auto &amp;&amp; __range =</b></code> <span class="t-spar">范围表达式</span> <code><b>;</b></code> <br>
</dd><dd><code><b>auto __begin =</b></code> <i>首表达式</i> <code><b>;</b></code><br>
</dd><dd><code><b>auto __end =</b></code> <i>尾表达式</i> <code><b>;</b></code><br>
</dd><dd><code><b>for ( ; __begin != __end; ++__begin) {</b></code> <br>
<dl><dd><span class="t-spar">范围变量声明</span> <code><b>= *__begin;</b></code> <br>
</dd><dd><span class="t-spar">循环语句</span> <br>
</dd></dl>
</dd><dd><code><b>} </b></code> <br>
</dd></dl>
<p><code><b>} </b></code> <br>
</p>
</td>
<td><span class="t-mark-rev t-since-cxx17">(C++17 起)</span><br><span class="t-mark-rev t-until-cxx20">(C++20 前)</span></td></tr>
<tr class="t-rev t-since-cxx20"><td>
<p><code><b>{</b></code><br>
</p>
<dl><dd><span class="t-spar">初始化语句</span><br>
</dd><dd><code><b>auto &amp;&amp; __range =</b></code> <span class="t-spar">范围表达式</span> <code><b>;</b></code> <br>
</dd><dd><code><b>auto __begin =</b></code> <i>首表达式</i> <code><b>;</b></code><br>
</dd><dd><code><b>auto __end =</b></code> <i>尾表达式</i> <code><b>;</b></code><br>
</dd><dd><code><b>for ( ; __begin != __end; ++__begin) {</b></code> <br>
<dl><dd><span class="t-spar">范围变量声明</span> <code><b>= *__begin;</b></code> <br>
</dd><dd><span class="t-spar">循环语句</span> <br>
</dd></dl>
</dd><dd><code><b>} </b></code> <br>
</dd></dl>
<p><code><b>} </b></code> <br>
</p>
</td>
<td><span class="t-mark-rev t-since-cxx20">(C++20 起)</span></td></tr>
</table>
<p>要迭代的序列或范围通过对 <span class="t-spar">范围表达式</span> 求值以确定。依次对序列的每个元素进行解引用，并赋值给具有 <span class="t-spar">范围变量声明</span> 中所给定的类型和名字的变量。
</p><p><i><code>首表达式</code></i> 和 <i><code>尾表达式</code></i> 定义如下：
</p>
<ul><li> 如果 <span class="t-spar">范围表达式</span> 是数组类型的表达式，那么 <i><code>首表达式</code></i> 是 <span class="t-c"><span class="mw-geshi cpp source-cpp">__range</span></span> 而 <i><code>尾表达式</code></i> 是 <span class="t-c"><span class="mw-geshi cpp source-cpp"><span class="br0">(</span>__range <span class="sy2">+</span> __bound<span class="br0">)</span></span></span>，其中 <code>__bound</code> 是数组的元素数目（如果数组大小未知或拥有不完整类型，那么程序非良构）
</li><li> 如果 <span class="t-spar">范围表达式</span> 是同时拥有名为 <span class="t-c"><span class="mw-geshi cpp source-cpp">begin</span></span> 以及名为 <span class="t-c"><span class="mw-geshi cpp source-cpp">end</span></span> 的成员的类类型 <code>C</code> 的表达式（不管这些成员的类型或可见性），那么 <i><code>首表达式</code></i> 是 <span class="t-c"><span class="mw-geshi cpp source-cpp">__range.<span class="me1">begin</span><span class="br0">(</span><span class="br0">)</span></span></span> 而 <i><code>尾表达式</code></i> 是 <span class="t-c"><span class="mw-geshi cpp source-cpp">__range.<span class="me1">end</span><span class="br0">(</span><span class="br0">)</span></span></span>；
</li><li> 否则，<i><code>首表达式</code></i> 是 <span class="t-c"><span class="mw-geshi cpp source-cpp">begin<span class="br0">(</span>__range<span class="br0">)</span></span></span> 而 <i><code>尾表达式</code></i> 是 <span class="t-c"><span class="mw-geshi cpp source-cpp">end<span class="br0">(</span>__range<span class="br0">)</span></span></span>，通过<a href="adl.html" title="cpp/language/adl">实参依赖查找</a>进行查找（不进行非实参依赖查找）。
</li></ul>
<p>正如传统循环一样，<a href="break.html" title="cpp/language/break">break 语句</a>可用于提早退出循环，且 <a href="continue.html" title="cpp/language/continue">continue 语句</a>能用于以下个元素重新开始循环。
</p>
<h3><span class="mw-headline" id=".E4.B8.B4.E6.97.B6.E8.8C.83.E5.9B.B4.E8.A1.A8.E8.BE.BE.E5.BC.8F">临时范围表达式</span></h3>
<p>如果 <span class="t-spar">范围表达式</span> 返回临时量，那么它的生存期延续到循环结尾，如绑定到转发引用 <b><code>__range</code></b> 所示，但要注意 <span class="t-spar">范围表达式</span> 中任何临时量生存期都<i>不</i>会延长。
</p>
<div dir="ltr" class="mw-geshi" style="text-align: left;"><div class="cpp source-cpp"><pre class="de1"><span class="kw1">for</span> <span class="br0">(</span><span class="kw4">auto</span><span class="sy3">&amp;</span> x <span class="sy4">:</span> foo<span class="br0">(</span><span class="br0">)</span>.<span class="me1">items</span><span class="br0">(</span><span class="br0">)</span><span class="br0">)</span> <span class="br0">{</span> <span class="coMULTI">/* .. */</span> <span class="br0">}</span> <span class="co1">// 如果 foo() 返回右值则为未定义行为</span></pre></div></div>
 <table class="t-rev-begin">
<tr class="t-rev t-since-cxx20"><td>
<p>此问题可用 <span class="t-spar">初始化语句</span> 变通解决：
</p>
<div dir="ltr" class="mw-geshi" style="text-align: left;"><div class="cpp source-cpp"><pre class="de1"><span class="kw1">for</span> <span class="br0">(</span>T thing <span class="sy1">=</span> foo<span class="br0">(</span><span class="br0">)</span><span class="sy4">;</span> <span class="kw4">auto</span><span class="sy3">&amp;</span> x <span class="sy4">:</span> thing.<span class="me1">items</span><span class="br0">(</span><span class="br0">)</span><span class="br0">)</span> <span class="br0">{</span> <span class="coMULTI">/* ... */</span> <span class="br0">}</span> <span class="co1">// OK</span></pre></div></div>
</td>
<td><span class="t-mark-rev t-since-cxx20">(C++20 起)</span></td></tr>
</table>
<h3><span class="mw-headline" id=".E6.B3.A8.E8.A7.A3">注解</span></h3>
<p>如果初始化器（<span class="t-spar">范围表达式</span>）是花括号初始化器列表，那么 <code>__range</code> 被推导为 <span class="t-lc">std::initializer_list&lt;&gt;&amp;&amp;</span>。
</p><p>在泛型代码中，使用推导的转发引用，如 <span class="t-c"><span class="mw-geshi cpp source-cpp"><span class="kw1">for</span> <span class="br0">(</span><span class="kw4">auto</span><span class="sy3">&amp;&amp;</span> var <span class="sy4">:</span> sequence<span class="br0">)</span></span></span>，是安全且受推荐的做法。
</p><p>如果范围类型拥有名为 <code>begin</code> 的成员和名为 <code>end</code> 的成员，那么使用成员解释方案。其中无视成员是类型、数据成员、函数还是枚举项及其可访问性。从而像 <span class="t-c"><span class="mw-geshi cpp source-cpp"><span class="kw1">class</span> meow <span class="br0">{</span> <span class="kw2">enum</span> <span class="br0">{</span> begin <span class="sy1">=</span> <span class="nu0">1</span>, end <span class="sy1">=</span> <span class="nu0">2</span><span class="br0">}</span><span class="sy4">;</span> <span class="coMULTI">/* 类的剩余部分 */</span> <span class="br0">}</span><span class="sy4">;</span></span></span> 的类不能用于基于范围的 for 循环，即使有命名空间作用域的 begin/end 函数存在。
</p><p>虽然通常在 <span class="t-spar">循环语句</span> 中使用声明于 <span class="t-spar">范围变量声明</span> 的变量，但并不要求这么做。
</p>
 <table class="t-rev-begin">
<tr class="t-rev t-since-cxx17"><td>
<p>从 C++17 开始，<span class="t-spar">首表达式</span> 和 <span class="t-spar">尾表达式</span> 的类型不必相同，而且实际上 <span class="t-spar">尾表达式</span> 的类型不必是迭代器：它只需要能与一个迭代器比较是否不等。这允许以一个谓词（例如“迭代器指向空字符”）对范围进行分界。
</p>
</td>
<td><span class="t-mark-rev t-since-cxx17">(C++17 起)</span></td></tr>
</table>
<p>当基于范围的 for 循环被用于一个具有写时复制语义的（非 const）对象时，它可能会通过（隐式）调用非 const 的 <code>begin()</code> 成员函数触发深层复制。
</p>
 <table class="t-rev-begin">
<tr class="t-rev t-since-cxx17"><td>
<p>如果想要避免这种行为（比如循环实际上不会修改这个对象），可以使用 <span class="t-lc"><a href="../utility/as_const.html" title="cpp/utility/as const">std::as_const</a></span>：
</p>
<div dir="ltr" class="mw-geshi" style="text-align: left;"><div class="cpp source-cpp"><pre class="de1"><span class="kw1">struct</span> cow_string <span class="br0">{</span> <span class="coMULTI">/* ... */</span> <span class="br0">}</span><span class="sy4">;</span> <span class="co1">// 写时复制的字符串</span>
cow_string str <span class="sy1">=</span> <span class="coMULTI">/* ... */</span><span class="sy4">;</span>
 
<span class="co1">// for(auto x : str) { /* ... */ } // 可能会导致深层复制</span>
 
<span class="kw1">for</span><span class="br0">(</span><span class="kw4">auto</span> x <span class="sy4">:</span> <a href="../utility/as_const.html"><span class="kw1121">std::<span class="me2">as_const</span></span></a><span class="br0">(</span>str<span class="br0">)</span><span class="br0">)</span> <span class="br0">{</span> <span class="coMULTI">/* ... */</span> <span class="br0">}</span></pre></div></div>
</td>
<td><span class="t-mark-rev t-since-cxx17">(C++17 起)</span></td></tr>
</table>
<h3><span class="mw-headline" id=".E5.85.B3.E9.94.AE.E8.AF.8D">关键词</span></h3>
<p><a href="../keyword/for.html" title="cpp/keyword/for"><tt>for</tt></a>
</p>
<h3><span class="mw-headline" id=".E7.A4.BA.E4.BE.8B">示例</span></h3>
<div class="t-example"><div class="t-example-live-link"><div class="coliru-btn coliru-btn-run-init">运行此代码</div></div>
<div dir="ltr" class="mw-geshi" style="text-align: left;"><div class="cpp source-cpp"><pre class="de1"><span class="co2">#include &lt;iostream&gt;</span>
<span class="co2">#include &lt;vector&gt;</span>
 
<span class="kw4">int</span> main<span class="br0">(</span><span class="br0">)</span> <span class="br0">{</span>
    <a href="../container/vector.html"><span class="kw1269">std::<span class="me2">vector</span></span></a><span class="sy1">&lt;</span><span class="kw4">int</span><span class="sy1">&gt;</span> v <span class="sy1">=</span> <span class="br0">{</span><span class="nu0">0</span>, <span class="nu0">1</span>, <span class="nu0">2</span>, <span class="nu0">3</span>, <span class="nu0">4</span>, <span class="nu0">5</span><span class="br0">}</span><span class="sy4">;</span>
 
    <span class="kw1">for</span> <span class="br0">(</span><span class="kw4">const</span> <span class="kw4">int</span><span class="sy3">&amp;</span> i <span class="sy4">:</span> v<span class="br0">)</span> <span class="co1">// 以 const 引用访问</span>
        <a href="../io/cout.html"><span class="kw1758">std::<span class="me2">cout</span></span></a> <span class="sy1">&lt;&lt;</span> i <span class="sy1">&lt;&lt;</span> <span class="st0">' '</span><span class="sy4">;</span>
    <a href="../io/cout.html"><span class="kw1758">std::<span class="me2">cout</span></span></a> <span class="sy1">&lt;&lt;</span> <span class="st0">'<span class="es1">\n</span>'</span><span class="sy4">;</span>
 
    <span class="kw1">for</span> <span class="br0">(</span><span class="kw4">auto</span> i <span class="sy4">:</span> v<span class="br0">)</span> <span class="co1">// 以值访问，i 的类型是 int</span>
        <a href="../io/cout.html"><span class="kw1758">std::<span class="me2">cout</span></span></a> <span class="sy1">&lt;&lt;</span> i <span class="sy1">&lt;&lt;</span> <span class="st0">' '</span><span class="sy4">;</span>
    <a href="../io/cout.html"><span class="kw1758">std::<span class="me2">cout</span></span></a> <span class="sy1">&lt;&lt;</span> <span class="st0">'<span class="es1">\n</span>'</span><span class="sy4">;</span>
 
    <span class="kw1">for</span> <span class="br0">(</span><span class="kw4">auto</span><span class="sy3">&amp;&amp;</span> i <span class="sy4">:</span> v<span class="br0">)</span> <span class="co1">// 以转发引用访问，i 的类型是 int&amp;</span>
        <a href="../io/cout.html"><span class="kw1758">std::<span class="me2">cout</span></span></a> <span class="sy1">&lt;&lt;</span> i <span class="sy1">&lt;&lt;</span> <span class="st0">' '</span><span class="sy4">;</span>
    <a href="../io/cout.html"><span class="kw1758">std::<span class="me2">cout</span></span></a> <span class="sy1">&lt;&lt;</span> <span class="st0">'<span class="es1">\n</span>'</span><span class="sy4">;</span>
 
    <span class="kw4">const</span> <span class="kw4">auto</span><span class="sy3">&amp;</span> cv <span class="sy1">=</span> v<span class="sy4">;</span>
 
    <span class="kw1">for</span> <span class="br0">(</span><span class="kw4">auto</span><span class="sy3">&amp;&amp;</span> i <span class="sy4">:</span> cv<span class="br0">)</span> <span class="co1">// 以转发引用访问，i 的类型是 const int&amp;</span>
        <a href="../io/cout.html"><span class="kw1758">std::<span class="me2">cout</span></span></a> <span class="sy1">&lt;&lt;</span> i <span class="sy1">&lt;&lt;</span> <span class="st0">' '</span><span class="sy4">;</span>
    <a href="../io/cout.html"><span class="kw1758">std::<span class="me2">cout</span></span></a> <span class="sy1">&lt;&lt;</span> <span class="st0">'<span class="es1">\n</span>'</span><span class="sy4">;</span>
 
    <span class="kw1">for</span> <span class="br0">(</span><span class="kw4">int</span> n <span class="sy4">:</span> <span class="br0">{</span><span class="nu0">0</span>, <span class="nu0">1</span>, <span class="nu0">2</span>, <span class="nu0">3</span>, <span class="nu0">4</span>, <span class="nu0">5</span><span class="br0">}</span><span class="br0">)</span> <span class="co1">// 初始化器可以是花括号初始化器列表</span>
        <a href="../io/cout.html"><span class="kw1758">std::<span class="me2">cout</span></span></a> <span class="sy1">&lt;&lt;</span> n <span class="sy1">&lt;&lt;</span> <span class="st0">' '</span><span class="sy4">;</span>
    <a href="../io/cout.html"><span class="kw1758">std::<span class="me2">cout</span></span></a> <span class="sy1">&lt;&lt;</span> <span class="st0">'<span class="es1">\n</span>'</span><span class="sy4">;</span>
 
    <span class="kw4">int</span> a<span class="br0">[</span><span class="br0">]</span> <span class="sy1">=</span> <span class="br0">{</span><span class="nu0">0</span>, <span class="nu0">1</span>, <span class="nu0">2</span>, <span class="nu0">3</span>, <span class="nu0">4</span>, <span class="nu0">5</span><span class="br0">}</span><span class="sy4">;</span>
    <span class="kw1">for</span> <span class="br0">(</span><span class="kw4">int</span> n <span class="sy4">:</span> a<span class="br0">)</span> <span class="co1">// 初始化器可以是数组</span>
        <a href="../io/cout.html"><span class="kw1758">std::<span class="me2">cout</span></span></a> <span class="sy1">&lt;&lt;</span> n <span class="sy1">&lt;&lt;</span> <span class="st0">' '</span><span class="sy4">;</span>
    <a href="../io/cout.html"><span class="kw1758">std::<span class="me2">cout</span></span></a> <span class="sy1">&lt;&lt;</span> <span class="st0">'<span class="es1">\n</span>'</span><span class="sy4">;</span>
 
    <span class="kw1">for</span> <span class="br0">(</span><span class="br0">[</span><span class="br0">[</span>maybe_unused<span class="br0">]</span><span class="br0">]</span> <span class="kw4">int</span> n <span class="sy4">:</span> a<span class="br0">)</span>  
        <a href="../io/cout.html"><span class="kw1758">std::<span class="me2">cout</span></span></a> <span class="sy1">&lt;&lt;</span> <span class="nu0">1</span> <span class="sy1">&lt;&lt;</span> <span class="st0">' '</span><span class="sy4">;</span> <span class="co1">// 不必使用循环变量</span>
    <a href="../io/cout.html"><span class="kw1758">std::<span class="me2">cout</span></span></a> <span class="sy1">&lt;&lt;</span> <span class="st0">'<span class="es1">\n</span>'</span><span class="sy4">;</span>
 
    <span class="kw1">for</span> <span class="br0">(</span><span class="kw4">auto</span> n <span class="sy1">=</span> v.<span class="me1">size</span><span class="br0">(</span><span class="br0">)</span><span class="sy4">;</span> <span class="kw4">auto</span> i <span class="sy4">:</span> v<span class="br0">)</span> <span class="co1">// 初始化语句（C++20）</span>
        <a href="../io/cout.html"><span class="kw1758">std::<span class="me2">cout</span></span></a> <span class="sy1">&lt;&lt;</span> <span class="sy2">--</span>n <span class="sy2">+</span> i <span class="sy1">&lt;&lt;</span> <span class="st0">' '</span><span class="sy4">;</span>
    <a href="../io/cout.html"><span class="kw1758">std::<span class="me2">cout</span></span></a> <span class="sy1">&lt;&lt;</span> <span class="st0">'<span class="es1">\n</span>'</span><span class="sy4">;</span>
 
    <span class="kw1">for</span> <span class="br0">(</span><span class="kw1">typedef</span> decltype<span class="br0">(</span>v<span class="br0">)</span><span class="sy4">::</span><span class="me2">value_type</span> elem_t<span class="sy4">;</span> elem_t i <span class="sy4">:</span> v<span class="br0">)</span>
    <span class="co1">// typedef 声明作为初始化语句（C++20）</span>
        <a href="../io/cout.html"><span class="kw1758">std::<span class="me2">cout</span></span></a> <span class="sy1">&lt;&lt;</span> i <span class="sy1">&lt;&lt;</span> <span class="st0">' '</span><span class="sy4">;</span>
    <a href="../io/cout.html"><span class="kw1758">std::<span class="me2">cout</span></span></a> <span class="sy1">&lt;&lt;</span> <span class="st0">'<span class="es1">\n</span>'</span><span class="sy4">;</span>
 
    <span class="kw1">for</span> <span class="br0">(</span><span class="kw1">using</span> elem_t <span class="sy1">=</span> decltype<span class="br0">(</span>v<span class="br0">)</span><span class="sy4">::</span><span class="me2">value_type</span><span class="sy4">;</span> elem_t i <span class="sy4">:</span> v<span class="br0">)</span>
    <span class="co1">// 别名声明作为初始化语句，同上（C++23）</span>
        <a href="../io/cout.html"><span class="kw1758">std::<span class="me2">cout</span></span></a> <span class="sy1">&lt;&lt;</span> i <span class="sy1">&lt;&lt;</span> <span class="st0">' '</span><span class="sy4">;</span>
    <a href="../io/cout.html"><span class="kw1758">std::<span class="me2">cout</span></span></a> <span class="sy1">&lt;&lt;</span> <span class="st0">'<span class="es1">\n</span>'</span><span class="sy4">;</span>
<span class="br0">}</span></pre></div></div>
<p>输出：
</p>
<div dir="ltr" class="mw-geshi" style="text-align: left;"><div class="text source-text"><pre class="de1">0 1 2 3 4 5 
0 1 2 3 4 5 
0 1 2 3 4 5 
0 1 2 3 4 5 
0 1 2 3 4 5 
0 1 2 3 4 5 
1 1 1 1 1 1 
5 5 5 5 5 5 
0 1 2 3 4 5 
0 1 2 3 4 5</pre></div></div> 
</div>
<h3><span class="mw-headline" id=".E7.BC.BA.E9.99.B7.E6.8A.A5.E5.91.8A">缺陷报告</span></h3>
<p>下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。
</p>
<table class="dsctable" style="font-size:0.8em">
<tr>
<th> DR
</th>
<th> 应用于
</th>
<th> 出版时的行为
</th>
<th> 正确行为
</th></tr>
<tr>
<td> <a rel="nofollow" class="external text" href="https://wg21.link/P0962R1">P0962R1</a>
</td>
<td> C++11
</td>
<td> 只要 begin 和 end 之一存在就使用成员解释方案
</td>
<td> 只有在两者都存在时才使用
</td></tr></table>
<h3><span class="mw-headline" id=".E5.8F.82.E9.98.85">参阅</span></h3>
<table class="t-dsc-begin">

<tr class="t-dsc">
<td>  <div class="t-dsc-member-div"><div><a href="../algorithm/for_each.html" title="cpp/algorithm/for each"> <span class="t-lines"><span>for_each</span></span></a></div></div>
</td>
<td>   应用函数到范围中的元素  <br> <span class="t-mark">(函数模板)</span> </td></tr>
</table>

<!-- 
NewPP limit report
Preprocessor visited node count: 2844/1000000
Preprocessor generated node count: 8486/1000000
Post‐expand include size: 59512/2097152 bytes
Template argument size: 20640/2097152 bytes
Highest expansion depth: 20/40
Expensive parser function count: 0/100
-->

<!-- Saved in parser cache with key mwiki1-mwiki_zh_:pcache:idhash:2745-0!*!0!!zh!*!zh!* and timestamp 20211107170150 -->
</div>                    <!-- /bodycontent -->
                                        <!-- printfooter -->
                    <div class="printfooter">
                    来自“<a href="https://zh.cppreference.com/mwiki/index.php?title=cpp/language/range-for&amp;oldid=72921">https://zh.cppreference.com/mwiki/index.php?title=cpp/language/range-for&amp;oldid=72921</a>”                    </div>
                    <!-- /printfooter -->
                                                            <!-- catlinks -->
                    <!-- /catlinks -->
                                                            <div class="visualClear"></div>
                    <!-- debughtml -->
                                        <!-- /debughtml -->
                </div>
                <!-- /bodyContent -->
            </div>
        </div>
        <!-- /content -->
        <!-- footer -->
        <div id="cpp-footer-base" class="noprint">
            <div id="footer">
                        <div id="cpp-navigation">
            <h5>导航</h5>
            <ul><li><a href="https://zh.cppreference.com/w/cpp/language/range-for">Online version</a></li><li>Offline version retrieved 2022-01-01 00:37.</li></ul></div>
                        <ul id="footer-info">
                                    <li id="footer-info-lastmod"> 本页面最后修改于2021年11月7日 (星期日) 06:45。</li>
                                    <li id="footer-info-viewcount">此页面已被浏览过76,131次。</li>
                            </ul>
                    </div>
        </div>
        <!-- /footer -->
        <script>if(window.mw){
mw.loader.state({"site":"loading","user":"missing","user.groups":"ready"});
}</script>
<script src="../../../common/skin_scripts.js"></script>
<script>if(window.mw){
mw.loader.load(["mediawiki.action.view.postEdit","mediawiki.user","mediawiki.page.ready","mediawiki.searchSuggest","mediawiki.hidpi","ext.gadget.MathJax","ext.gadget.ColiruCompiler"], null, true);
}</script>
<script src="../../../common/site_scripts.js"></script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-2828341-1']);
_gaq.push(['_setDomainName', 'cppreference.com']);
_gaq.push(['_trackPageview']);
</script><!-- Served in 0.075 secs. -->
	</body>
<!-- Cached 20211107193109 -->
</html>